/**
 * 
 */
package Project2.cs342.project1.mathNotebook.data;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Collection;

import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

import Project2.cs342.project1.mathNotebook.notebook.NotebookEntry;

/**
 * Writes Notebook entries to an XML file
 * @author Jared Schlicht
 *
 */
public class XMLNotebookWriter implements NotebookWriter {
    private OutputStream outputStream;
    
    public XMLNotebookWriter(OutputStream outputStream) {
	this.outputStream = outputStream;
    }
    
    /**
     * @see cs342.project1.mathNotebook.data.NotebookWriter#writeAll(java.util.Collection)
     */
    @Override
    public boolean writeAll(Collection<NotebookEntry> entries) {
	boolean wasSuccessful = true;
	
	XMLOutputFactory factory = XMLOutputFactory.newInstance();
	try {
		XMLStreamWriter writer = factory.createXMLStreamWriter(outputStream);
		writer.writeStartDocument();
		writer.writeStartElement("notebook");
		for (NotebookEntry entry : entries) {
			writer.writeStartElement("formula");
			writer.writeAttribute("equation", entry.functionString);
			for (Double tangentPoint : entry.tangentPoints) {
			    writer.writeStartElement("tangent");
			    writer.writeAttribute("point", tangentPoint.toString());
			    writer.writeEndElement();
			}
			writer.writeEndElement();
		}
		writer.writeEndElement();
		writer.writeEndDocument();
		writer.flush();
	} catch (XMLStreamException e) {
		wasSuccessful = false;
	}
	
	return wasSuccessful;
    }

    /**
     * Closes the output stream object
     */
    @Override
    public void close() {
	try {
	    this.outputStream.close();
	} catch (IOException e) {}
    }

}
